package com.example.demo.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author chensixiang chensixiang1234@gmail.com
 */
@RestController
@RequestMapping("/ttl")
@Slf4j
@RequiredArgsConstructor
public class SendMessageController {

    private final RabbitTemplate rabbitTemplate;

    @GetMapping("/sendMessage/{message}")
    public String sendMessage(@PathVariable String message) {
        log.info("*******当前时间：{}，发送一条消息给两个TTL队列：{}", new Date(), message);
        rabbitTemplate.convertAndSend("X", "XA", "消息来自ttl为10s的队列：" + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自ttl为40s的队列：" + message);
        return "";
    }

    @GetMapping("/time/{message}/{time}")
    public String sendMessageWithTtl(@PathVariable("message") String message, @PathVariable("time") String time) {
        log.info("*******当前时间：{}，发送一条时长{}ms的消息给一个队列QC：{}", new Date(), time, message);
        rabbitTemplate.convertAndSend("X","XC",message,msg -> {
            msg.getMessageProperties().setExpiration(time);
            return msg;
        });
        return "";
    }

    @GetMapping("/delay/{message}/{time}")
    public String sendMessageWithDelay(@PathVariable("message") String message, @PathVariable("time") Integer time) {
        log.info("*******当前时间：{}，发送一条时长{}ms的消息给一个延迟队列delayed.queue：{}", new Date(), time, message);
        rabbitTemplate.convertAndSend("delayed.exchange","delayed.routingkey",message,msg -> {
            msg.getMessageProperties().setDelay(time);
            return msg;
        });
        return "";
    }
}
